<template>
  <div class="container">
    <div class="sidebar">
      <!-- <el-tree :data="leveldata" :props="dPs"  @node-click="handleNodeClick" default-expand-all :highlight-current="highlightBd" node-key="id" :current-node-key='currentKey' ref="treeRef"></el-tree> -->
      <el-dropdown  @command="handleCommand">
        <el-button style="margin-top: 10px; margin-left:10px">
          传感器<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown"  type="primary" @click="handleClickDevice">
          <el-dropdown-item v-for="item in deviceList" :key="item.value" :command="item">{{ item.name }}</el-dropdown-item>
          <!-- <el-dropdown-item>狮子头</el-dropdown-item>
          <el-dropdown-item>螺蛳粉</el-dropdown-item>
          <el-dropdown-item disabled>双皮奶</el-dropdown-item>
          <el-dropdown-item divided>蚵仔煎</el-dropdown-item> -->
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="content">
      <!-- activeName -->
      <el-tabs v-model="activeName"  @tab-click="handleClick">
        <!-- <el-button @click="getList"> get</el-button> -->
      
        <el-tab-pane :label="`泥位数据图 ${choseDeviceName}`" name="first">
          <div class="chart-container">
            <chart v-loading="loading" height="100%" width="100%" :chartData="chartData" :chartRiqi="chartRiqi" />
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane label="泥位波动图" name="second"></el-tab-pane> -->
        <!-- <el-tab-pane label="刨面内侧点缩略图" name="third"></el-tab-pane> -->
      </el-tabs>
    </div>
    
    
  </div>
</template>

<script>
import chart from '../../components/charts/Mix-mudgauge.vue'
import { getDeviceLevelData, listDevice, listNewDevice, sensorPointList  } from "@/api/screen/device";

export default {
  name: 'graph',
  components: { chart },
  data() {
    return {
        choseDeviceName: '',
        currentKey: 0,
        highlightBd: true,
        activeName: 'first',
        // chatData: [
        //   // 150, 230, 224, 218, 135, 147, 262
        // ],
        chartRiqi: [
          // '2023-11-11', '2023-11-12', '2023-11-13', '2023-11-14', '2023-11-15', '2023-11-16', '2023-11-17'
        ],
        deviceLevelDataList: [],
        leveldata: [],
        activeName: 'first',
        chartData: [
          // 150, 230, 224, 218, 135, 147, 280
        ],
        deviceList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        elTreeData: [],
        loading: true,
        username: '',
      }
  },
  computed: {
    dPs() {
      return {
        children: 'children',
        label: 'label'
      };
    }
  },
  mounted() {
    // this.getList()
    this.username = this.$store.state.user.name
    if(this.username == 'maguan') {
        this.getsensorPoint('马关')
      }
      else if (this.username == 'guanxi'){
        this.getsensorPoint('关西')
      }
      else {
        this.getsensorPoint()
      }


    // this.getsensorPoint();
  },
  methods: {
    //站点列表
    getsensorPoint(e) {
        sensorPointList({name: e, sensorName: '泥位'}).then(response=> {
          this.deviceList = response.rows
          console.log('deviceListMud',this.deviceList ) 
          // this.convertToElTree()
          this.groupByDeviceId()
          // 选择并处理第一个树节点
          if (this.deviceList?.length > 0 && this.deviceList[0].children && this.deviceList[0].children?.length > 0) {
            const firstNodeId = this.deviceList[0].children[0].id;
            this.handleNodeClick({id: firstNodeId});
          }

          console.log('this.deviceList', this.deviceList)
          // monitordevicecode 所属监测点
          // monitordevicename 设备类型
          // deviceid  设备id
          this.total = response.total;
          this.loading = false;

        })
      },
      handleClick (tab, event) {
      console.log(tab, event)
    },
     /** 查询设备列表 */
    // getList() {
    //   this.loading = true;
    //   listNewDevice({name:'levelData', pageSize:20}).then(response => {
    //     console.log('deviceListMud',response.rows) 
    //     this.deviceList = response.rows
    //     // this.convertToElTree()
    //     this.groupByDeviceId()
    //     // 选择并处理第一个树节点
    //     if (this.leveldata?.length > 0 && this.leveldata[0].children && this.leveldata[0].children?.length > 0) {
    //     const firstNodeId = this.leveldata[0].children[0].id;
    //     this.handleNodeClick({id: firstNodeId});
    //      }

    //     console.log('this.deviceList', this.deviceList)
    //     // monitordevicecode 所属监测点
    //     // monitordevicename 设备类型
    //     // deviceid  设备id
    //     this.total = response.total;
    //     this.loading = false;
    //     }
    //   );
    // },
    // 函数根据 deviceId 对设备进行分组
    groupByDeviceId(devices = this.deviceList) {
      
        return devices.reduce((groups, device) => {
          const { name } = device;
          if (!groups[name]) {
            groups[name] = [];
          }
          groups[name].push({
            label: device.deviceName,
            ...device
          });
          console.log('groups', groups)
          this.groupedDevices = groups


          // 将分组转换为 el-tree 的数据格式（每个分组一个树）
          this.leveldata = Object.keys(this.groupedDevices).map(name => {
            return {
              label: `位置编号 ${name}`,
              children: this.groupedDevices[name]
              // children: this.groupedDevices[{ id: device.deviceId, label: device.deviceName  }]
            };
          });
          return groups;
        }, {});
      },
    /** 查询降雨量设备数据详情 */
    // getDeviceLevelData(e) {
    //   this.loading = true;
    //   getDeviceLevelData({deviceId:e, isAsc:'desc', orderByColumn:'createTime'}).then(response => {
    //     console.log('deviceLevelDataList',response.rows) 
    //     this.loading = false
    //     // let resList = response.rows
    //     // this.deviceLevelDataList = resList.reverse()
    //     this.deviceLevelDataList = response.rows
    //     this.chartRiqi = this.deviceLevelDataList.map(item=> {return item.createTime})
    //     this.chatData = this.deviceLevelDataList.map(item=> {return item.tag})
    //     console.log('this.chatData', this.chatData, this.chartRiqi)
    //     }
    //   );
    // },
    handleNodeClick(leveldata) {
      console.log('leveldata-tree', leveldata);
      console.log('leveldata-tree', leveldata.id);
      console.log('leveldata-tree', leveldata[0].id);
      if( leveldata.id == null) {
        console.log('null')
      } else {
        this.getDeviceLevelData(leveldata.deviceId)
        this.currentKey = leveldata.deviceId
        this.$nextTick(() => {
          this.$refs['treeRef'].setCurrentKey(this.currentKey)
        })
      }
    },
    convertToElTree(e = this.deviceList) {
        const tempMap = new Map(); // 临时 Map 用于合并相同项
        // 遍历设备列表
        e.forEach(device => {
          if (tempMap.has(device.monitorDeviceCode) || tempMap.has(device.monitorDeviceName)) {
             // 如果存在相同设备名称的项，则合并
             const existingDevice = tempMap.get(device.monitorDeviceCode);
            //  const existingMonitordevicename = tempMap.get(device.monitordevicename);
             existingDevice.children.push({ id: device.deviceId, label: device.deviceName });
          } else {
             // 如果不存在相同设备名称的项，则创建新节点
             tempMap.set(device.monitorDeviceCode, {
              label: device.monitorDeviceCode,
              children: [{ id: device.deviceId, label: device.deviceName  }]
            });
            // 如果不存在相同设备名称的项，则创建新节点
            
          }
        });
        
        // 将 Map 转换为数组，存储到 elTreeData 中
        this.elTreeData = Array.from(tempMap.values());

        this.leveldata = this.elTreeData
        console.log('this.elTreeData', this.elTreeData)
      },
      handleClickDevice(e) {
        console.log('eee', e)
      },
      handleCommand(command) {
        console.log('command', command)
        this.choseDeviceName = command.name
        listNewDevice({strPointId: command.strId, pageSize:500, isAsc: 'desc',orderByColumn: 'time'}).then(response => {
        console.log('deviceLevelDataList',response.rows) 
        this.loading = false
        this.deviceLevelDataList = response.rows
        this.chartRiqi = this.deviceLevelDataList.map(item=> {return item.createTime})
        this.chartData = this.deviceLevelDataList.map(item=> {return ((item.resultData.substr(0, item.resultData.length-1)).split(':'))[1] })
        // let resList = response.rows
        // this.deviceLevelDataList = resList.reverse()
        // this.deviceLevelDataList = response.rows
        // this.chartRiqi = this.deviceLevelDataList.map(item=> {return item.createTime})
        // this.chatData = this.deviceLevelDataList.map(item=> {return item.tag})
        //  console.log('this.chatData', this.chatData, this.chartRiqi)
          }
        );
      }

  }
}
</script>

<style scoped>
.el-tree-node:focus > .el-tree-node__content {
  color:  #409eff;
  /* transition: background 1s; */
}

.container {
  display: flex;
}

  
.sidebar {
  width: 200px; /* Adjust the width as per your layout */
  height: 100vh;
}

.content {
  flex: 1;
  height: 100vh;
}


.chart-container{
position: relative;
width: 100%;
height: 80vh;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>